<?php
/**
 * Nguoi tao: Tuanpm
 * Ngay tao: 20/02/2013
 * Y nghia: Cap nhat xu ly tai lieu hoc tap
 */	
class Web_IndexController extends  Zend_Controller_Action {
	public function init(){
		Zend_Loader::loadClass('mtl_modSearch');
		Zend_Loader::loadClass('listxml_modTree');
		Zend_Loader::loadClass('Zend_Json');	    
		//Load cau hinh thu muc trong file config.ini
        $tempDirApp = Zend_Registry::get('conDirApp');
		$this->_dirApp = $tempDirApp->toArray();
		$this->view->dirApp = $tempDirApp->toArray();
		//Lay duong dan thu muc goc (path directory root)
		$this->view->baseUrl = $this->_request->getBaseUrl() . "/public/";
		if (!$this->_request->isXmlHttpRequest()){
			//Cau hinh cho Zend_layout
			Zend_Layout::startMvc(array(
				    'layoutPath' => $this->_dirApp['layout'],
				    'layout' => 'web'			    
				    ));	
			//Load cac thanh phan cau vao trang layout (index.phtml)
			$response = $this->getResponse();
			//Ky tu dac biet phan tach giua cac phan tu
			$this->view->delimitor 	= "!~~!";	
			//Load cau hinh thu muc trong file config.ini de lay ca hang so dung chung
	        $tempConstPublic = Zend_Registry::get('ConstPublic');
			$this->_ConstPublic = $tempConstPublic->toArray();	
			//Lay cac hang so su dung trong JS public
			$objConfig = new Efy_Init_Config();
			$objConst = new Efy_Init_Const();
			$this->view->JSPublicConst = $objConfig->_setJavaScriptPublicVariable();		
			$this->view->UrlAjax = $objConfig->_setUrlAjax();
			$arrConst = $objConst->_setProjectPublicConst();
			$this->view->arrConst = $arrConst;
			// Load tat ca cac file Js va Css
			$this->view->LoadAllFileJsCss = Efy_Publib_Library::_getAllFileJavaScriptCss('','efy-js','web/home.js,efyxml.js',',','js');			
			$objFunction = New Efy_Function_RecordFunctions();	
			$this->view->leftTree = $objFunction->genLeftTree();
			//Load right menu
			$this->view->arrRightMenu = $objFunction->getAllObjectbyListCode('','DM_SACH');
			//Load tac gia
			$arrAuthors = $objFunction->getAllObjectbyListCodeFull('','DM_TAC_GIA');
			$arrput = array();
			foreach ($arrAuthors as $key => $author) {
				if ($author['DISPLAY_HOME']) {
					array_push($arrput, $author);
				}
			}
			$this->view->arrAuthors = $arrput;

			
			//Dinh nghia current modul code
			$this->view->currentModulCode = "REMINDER";
			$this->view->currentModulCodeForLeft = $this->_request->getParam('action');
	        $response->insert('header', $this->view->renderLayout('header_web.phtml','./application/views/scripts/'));
			$response->insert('left', $this->view->renderLayout('left_web.phtml','./application/views/scripts/'));
			$response->insert('right', $this->view->renderLayout('right_web.phtml','./application/views/scripts/'));
	        $response->insert('footer', $this->view->renderLayout('footer_web.phtml','./application/views/scripts/')); 			
		}else{
			$result = array();
			$result = Efy_Publib_Library::_getAllFileJavaScriptCssArray('','efy-js'
				,'mtl/publicTree.js,ajaxupload.3.5.js,fg.menu.js,jquery.multiselect.js,chosen'
				,','
				,'js'
				,$result);
			$result = Efy_Publib_Library::_getAllFileJavaScriptCssArray(''
					,'efy-style'
					,'fg.menu.css,chosen/chosen.css,jquery.multiselect.css'
					,','
					,'css'
					,$result);	
			$result = Efy_Publib_Library::_getAllFileJavaScriptCssArray('','efy-js','mtl/reminder.js',',','js',$result);		
			$this->view->arrJsCss = Zend_Json::encode($result);	
			$baseurl=$this->_request->getbaseurl();			 
		}
	}	
	/**
	 * @author: Tuanpm
	 * @see: 20/02/2013
	 * @todo: Hien thi danh sach nhac viec
	 * Enter description here ...
	 */
	public function indexAction(){
		$objFunction = New Efy_Function_RecordFunctions();
		$objEfyLib = new Efy_Library();
		if (!isset($_SESSION['TREE_TRAINING'])) {
			$objEfyLib->setsessiontree();
		}
		$this->view->arrListItem = $objFunction->getAllObjectbyListCode('','DM_SO_HS_TREN_TRANG');
	}
	public function trainingAction(){
		$arrWards = array();		
		$objFunction = New Efy_Function_RecordFunctions();	

		$this->view->arrListItem = $objFunction->getAllObjectbyListCode('','DM_SO_HS_TREN_TRANG');
		$this->view->leftTree = $objFunction->genLeftTree();
		$this->view->titleBody = 'DANH SÁCH BÀI GIẢNG';
		$this->view->iCurrentPage = 1;
		$this->view->iNumberRecordPerPage = 15;
        //$arrTemp =  $this->_request->getParams();
	}

	public function indexdataAction(){
		//Tao doi tuong
		$objFunction = New Efy_Function_RecordFunctions();
		$objconfig = new Efy_Init_Config();	
		$objModel = new mtl_modSearch();		
		$arrResult = array();
		$typeSearch = $this->_request->getParam('type','');
		$typeTree = $this->_request->getParam('typehdn','');
		$path = $this->_request->getParam('hdnpath','');
		$link_db_user  = $objconfig->_setDbLinkUser();
		// $ownerCode = Efy_Publib_Library::_getItemAttrById($_SESSION['arr_all_staff'],$_SESSION['staff_id'],'ownerCode');
		$ownerCode = 'QHB';
		$StaffId = $_SESSION['staff_id'];
		if ($typeSearch == 'on') $typeSearch = 'All';
			else $typeSearch = '';
		$TD18 = $this->_request->getParam('TD18','');
		$TD18 = Efy_Publib_Library::_Replace_VietNamese($TD18);
		$TD18 = strtolower($TD18);
		// Lay duong dan
		$td03 = $this->_request->getParam('TD03','');
		$breadcrumbs = $this->_genbreadindex($td03);		
		//Mảng lưu tiêu chí tìm kiếm
		$arrParameter = array(
			'TD03'							=> $td03,
            'code'                     		=> $this->_request->getParam('code',''),
            'author'                       => $this->_request->getParam('author',''),
			'TD18'              		    => $TD18,
			'type'                 			=> $typeSearch,
			'TR06'                			=> $typeTree,
			'TR09'                		 	=> $ownerCode,
			'TD21'							=> $StaffId,
            'sstaff_permisstion'            => $_SESSION['STAFF_PERMISSTION'],
			'link_db_user'					=> $link_db_user,
			'iCurrentPage'         			=> $this->_request->getParam('hdn_current_page','1'),
			'iNumberRecordPerPage' 			=> $this->_request->getParam('hdn_record_number_page','15')				
		);
		$arrStatus = $objFunction->getAllObjectbyListCode($_SESSION['OWNER_CODE'],'DM_TRANG_THAI');
		$sp = 'mTL_SearchTrainingGetAll';
		$arrResult = $objModel->mTLSPRun($sp,$arrParameter, 1,0);
		if ($arrResult)
			for ($i=0; $i < sizeof($arrResult); $i++) { 			
				$arrResult[$i]['TD23'] = ($arrResult[$i]['TD23'] != null)?$arrResult[$i]['TD23']:'';
				$arrResult[$i]['TD19'] = ($arrResult[$i]['TD19'] != null)?str_replace('!@!', ', ', $arrResult[$i]['TD19']):'';
				$arrResult[$i]['TD06'] = Efy_Library::_getNameByCode($arrStatus,$arrResult[$i]['TD06'],'C_NAME');
				//Lay file dinh kem
				$fileNameThumb = isset($arrResult[$i]['C_FILENAME_THUMB']) ? $arrResult[$i]['C_FILENAME_THUMB'] :'';
				// $fileNameThumb = $arrResult[$i]['C_FILENAME_THUMB'];
				if(is_null($fileNameThumb) || $fileNameThumb ==''){
					$arrResult[$i]['C_FILENAME_THUMB'] = $objconfig->_setAttachFileUrlPath().'default/default.jpg';
				}else{
					$arrFilename = explode('!~!',$fileNameThumb);
					$file_id   = explode("_", $arrFilename[0]);
		        	$srcThumBnail = $objconfig->_setAttachFileUrlPath() . $file_id[0] . "/" . $file_id[1] . "/" . $file_id[2] . "/" . $fileNameThumb;
		        	$pathFileExist = '..' . str_replace("/","\\",$srcThumBnail);
					if(file_exists($pathFileExist)) 
						$arrResult[$i]['C_FILENAME_THUMB'] = $srcThumBnail;
					else
						$arrResult[$i]['C_FILENAME_THUMB'] = $objconfig->_setAttachFileUrlPath().'default/default.jpg';
				}
			}
		echo Zend_Json::encode(array('breadcrumbs'=>$breadcrumbs,'arrResult'=>$arrResult));
		$this->getHelper('viewRenderer')->setNoRender();  		
	}

	private function _genbreadindex($pk_tree){
		$objEfyDBConnection = new Efy_DB_Connection();
		$arrResul = $objEfyDBConnection->EfyLibQueryDb(array('pk_tree' => $pk_tree), 'mTL_getSubParentNode', true);
		$breadcrumb = '';
		$breadcrumb .='<ul style="">';
		if($arrResul){
			$iTotal = sizeof($arrResul);
			for ($i=$iTotal-1; $i >=0 ; $i--) {
				$href = '' ;
				if ($i== ($iTotal-1)) {
					$href = 'onclick="javaScript:goto_url(\''.$this->_request->getBaseUrl().'/web/index/'.'\')"';
				}
				$text = $arrResul[$i]['C_NAME'] .'<span>></span>';
				if ($i==0) {
					$text = $arrResul[$i]['C_NAME'];
				}
				$breadcrumb .= '<li '.$href.' class="alowclick alck" pktree="'.$arrResul[$i]['PK_TREE'].'">'. $text.'</li>';
			}
		} else {
			$href = 'onclick="javaScript:goto_url(\''.$this->_request->getBaseUrl().'/web/index/'.'\')"';
			$breadcrumb .= '<li '.$href.' class="alck" >NGHIÊN CỨU KHOA HỌC</li>';
		}
		$breadcrumb .='</ul>';
		return $breadcrumb;
	}
	public function getChildNode($idNode,$arrTreeGetAll){
		$arrOutput = array();
		foreach ($arrTreeGetAll as $key => $value) {
			if($value['FK_OBJECT'] == $idNode){
				array_push($arrOutput, array('attr'=>array(
												'id'=>$value['PK_OBJECT']
												,'rel'=>'folder'
											),
											'data'=>$value['TR04'],
											'state'=>'closed'
				));
			}
		}
		return $arrOutput;
	}
	public function loadtreeAction(){
		$objTree	= new Listxml_modTree();
		$arrTree = '';
		$sType = $this->_request->getParam('sType',null);
		$searchNodes = $this->_request->getParam('searchNodes',null);
		$ownerCode = Efy_Publib_Library::_getItemAttrById($_SESSION['arr_all_staff'],$_SESSION['staff_id'],'ownerCode');
		$arrParameter = array(
			'status'=>'HOAT_DONG'
			,'txtFullTextSearch'=>''
			,'type'=>$sType
			,'sOwner_code'=>$ownerCode
		);
		if(!isset($_SESSION['TREE_TRAINING'])) {
			$objTree	= new Listxml_modTree();
			$_SESSION['TREE_TRAINING'] = $objTree->mTL_TreeGetAll($arrParameter);
		}
		$arrTreeGetAll = $_SESSION['TREE_TRAINING'];
		$idNode = $this->_request->getParam('id',null);
		$arrTree = $this->getChildNode($idNode,$arrTreeGetAll);
		if ($searchNodes != '')
			$arrTree = $arrTreeGetAll;
		echo json_encode($arrTree);
		$this->getHelper('viewRenderer')->setNoRender();  
	}
	public function viewAction(){
		$objFunction = New Efy_Function_RecordFunctions();
		$objLib = new Efy_Library();
		$objModel = new mtl_modSearch();
		$objconfig = new Efy_Init_Config();
		
		$PkDoc = $this->_request->getParam('PkDoc',null);
		$typeTree = $this->_request->getParam('typehdn','');
		$arrParameter = array('PkDoc' => $PkDoc);
		$arrTG = $objFunction->getAllObjectbyListCode($_SESSION['OWNER_CODE'],'DM_TAC_GIA');
		$sp = 'mTL_SearchTrainingGetSingle';
		$arrResult = $objModel->mTLSPRun($sp,$arrParameter, 0,0);
		$arrResult['TD23'] = ($arrResult['TD23'] != null)?$arrResult['TD23']:'';
		$arrResult['TD19'] = ($arrResult['TD19'] != null)?str_replace('!@!', ', ', $arrResult['TD19']):'';
		$arrAuthors = explode(',', $arrResult['C_TAC_GIA']);
		$authorNames = '';
		foreach ($arrAuthors as $key => $author) {
			$authorNames = Efy_Library::_getNameByCode($arrTG,$author,'C_NAME').'<br>';
		}
		$arrResult['C_TAC_GIA'] = $authorNames;
		$sFile = '';
		//Lay file dinh kem
		$filedocument 	= $arrResult['C_FILE_DOCUMENT'];
		$fileflash 	= $arrResult['C_FILE_FLASH'];
		$viewdocument = '';
		$videos = array();
		$viewdocument = $this->createviewdocument($arrResult);
		$breadcrumbs = $this->_genbreadcrumbs($arrResult['TD03'], $arrResult['TD02']);
		$this->view->breadcrumbs = $breadcrumbs;
		$this->view->viewdocument = $viewdocument;
		$this->view->arrResult = $arrResult;
	}

	private function getpathfile($urlPath, $fileName) {
		$href ='';
		if(!(is_null($fileName) || $fileName =='')){
			$arrFilename = explode('!~!',$fileName);
			$file_id   = explode("_", $arrFilename[0]);
        	$href = $urlPath . $file_id[0] . "/" . $file_id[1] . "/" . $file_id[2] . "/" . $fileName;
        	$pathFileExist = '..' . str_replace("/","\\",$href);
        	if(!file_exists($pathFileExist)) $href ='';
		}
		return $href;
	}

	private function _genbreadcrumbs($pk_tree, $name){
		$objEfyDBConnection = new Efy_DB_Connection();
		$arrResul = $objEfyDBConnection->EfyLibQueryDb(array('pk_tree' => $pk_tree), 'mTL_getSubParentNode', true);
		$breadcrumb = '';
		$breadcrumb .='<ul>';
		if($arrResul){
			$iTotal = sizeof($arrResul);
			for ($i=$iTotal-1; $i >=0 ; $i--) {
				$href = '' ;
				if ($i== ($iTotal-1)) {
					$href = 'onclick="javaScript:goto_url(\''.$this->_request->getBaseUrl().'/web/index/'.'\')"';
				}
				$text = $arrResul[$i]['C_NAME'] .'<span>></span>';
				$breadcrumb .= '<li '.$href.' class="alowclick alck" pktree="'.$arrResul[$i]['PK_TREE'].'">'. $text.'</li>';
			}
		}
		$breadcrumb .= '<li>'. $name.'</li>';
		$breadcrumb .='</ul>';
		return $breadcrumb;
	}

	public function parseAttachFile($strFileList, $deliFileList = '!#~$|*', $deliFileName = '!~!', $sPathLink, $pkdoc){
		
		$strFileName = explode($deliFileList,$strFileList);		
		$fileAttach = '';
		$documents = array();
		for($i =0; $i < sizeof($strFileName); $i ++){
			$arrFileName = explode($deliFileName,$strFileName[$i]);			
			$fileName    = $arrFileName[1];
			$fileID 	 = $arrFileName[0];
			$arrFileLink = explode('_',$fileID);
			$fileLink = $sPathLink . $arrFileLink[0] . "/" . $arrFileLink[1] . "/" . $arrFileLink[2] . "/" . $strFileName[$i];

			$pathFileExist = '..' . str_replace("/","\\",$fileLink);			
			if(file_exists($pathFileExist)){
				$fileExtensiona = explode('.', $fileName);
				$fileExtension = end($fileExtensiona);
				$arrTemp = array('link'=>$fileLink,'name'=>$fileName, 'id'=>$pkdoc);
				array_push($documents,$arrTemp);
			}
			// 
		}
		return $documents;
	}

	private function createviewdocument($data){
		
		$objconfig = new Efy_Init_Config();
		$sesAccount = new Zend_Session_Namespace('Account');

		$srcword = $objconfig->_setImageUrlPath().'word-small.gif';
		$srcpdf = $objconfig->_setImageUrlPath().'pdf-small.gif';
		$srcxls = $objconfig->_setImageUrlPath().'xls-small.gif';
		$srcppt = $objconfig->_setImageUrlPath().'ppt-small.png';
        $srcunknow = $objconfig->_setImageUrlPath().'unknown-small.png';
        $arrFileName = explode("!~!",$data['C_FILE_DOCUMENT']);			
		$documentname    = $arrFileName[1];
		$string ='';
		$string .= '<div style="padding-bottom:20px;">';
		$arr = explode('.', $data['C_FILE_DOCUMENT']);
		$type = end($arr);
		$type = strtolower($type);
		switch ($type) {
			case 'xls':
			case 'xlsx':
			case 'XLS':
			case 'XLSX':
                $flag= 1;
				$src = $srcxls;
				break;
			case 'ppt':
			case 'pptx':
			case 'PPT':
			case 'PPTX':
                $flag= 1;
				$src = $srcppt;
				break;
				
			case 'pdf':
			case 'PDF':
                $flag= 1;
				$src = $srcpdf;
				break;
            case 'doc':
            case 'DOC':
            case 'docx':
            case 'DOCX':
                $flag= 1;
                $src = $srcword;
                break;
            default:
                $flag= 0;
                $src = $srcunknow;
                break;
		}
		$cldownload = 'showmodallogin()';
		$clview 	= 'showmodallogin()';
        $id = $sesAccount->id;
        if (is_null($data['C_GROUP_USER_DOWN']) || $data['C_GROUP_USER_DOWN'] == ''){
        	if (isset($sesAccount->id)) { 
	        	$cldownload ='downloaddocument(\''.$data['C_FILE_DOCUMENT'].'\')';
	        	$clview 	='readdocument(\''.$data['C_FILE_FLASH'].'\')';
        	}
        }else{
            if(isset($sesAccount->id)){            	
            	if(Efy_Library::checkroles('DOWN_'.$sesAccount->role, $data['C_GROUP_USER_DOWN'])) {
            		$cldownload ='downloaddocument(\''.$data['C_FILE_DOCUMENT'].'\')';
            	}else{
            		$cldownload ='notdownload()';
            	} 
            	if(Efy_Library::checkroles('VIEW_'.$sesAccount->role, $data['C_GROUP_USER_VIEW'])) {
            		$clview ='readdocument(\''.$data['C_FILE_FLASH'].'\')';
            	}else{
            		$clview ='notview()';
            	}           	
			}
        }
        $string .= '<div class= "document_view"><img alt="Word-logo-small" src="'.$src.'"><label>'.$documentname.'</label>';
        $string .= '<a href="#" title="Xem tư liệu" class="viewdocument" onclick="'.$clview.'"> </a>';
        $string .= '<a href="#" title="Tải tư liệu" class="download" onclick="'.$cldownload.'"> </a></div>';
        $string .= '<div id="preview-doc"></div>';
    	$string .= '</div></div>';

		$string .= '</div>';
		return $string;
	}
	public function loadcommentAction(){
		$objFunction = New Efy_Function_RecordFunctions();
		$objModel = new mtl_modSearch();
		$PkDoc = $this->_request->getParam('PkDoc',null);
		$PkComment = $this->_request->getParam('PkComment',null);
		$staffId = $_SESSION['staff_id'];
		$arrParameter = array('RC01'=>$PkComment
								,'RC02' => $PkDoc
								,'staffId' 		=> $staffId);
		$arrCommentGetAll = $objModel->mTLSPRun('mTL_CommentGetAll',$arrParameter, 1,0);
		echo Zend_Json::encode($arrCommentGetAll);
		$this->getHelper('viewRenderer')->setNoRender(); 
	}
	public function updatecmmtAction(){
		$objFunction = New Efy_Function_RecordFunctions();
		$objModel = new mtl_modSearch();
		$PkDoc = $this->_request->getParam('PkDoc',null);
		$RC01 = $this->_request->getParam('PkComment',null);
		$cmmt = $this->_request->getParam('cmmt',null);
		$sStaffName = Efy_Publib_Library::_getItemAttrById($_SESSION['arr_all_staff'],$_SESSION['staff_id'],'position_code'). ' - '.Efy_Publib_Library ::_getItemAttrById($_SESSION['arr_all_staff'],$_SESSION['staff_id'],'name');
		$sStaffId = Efy_Publib_Library::_getItemAttrById($_SESSION['arr_all_staff'],$_SESSION['staff_id'],'id');
		$arrParameter = array(
			'RC01'			=> $RC01,
			'RC02'			=> $PkDoc,
			'RC03'			=> $sStaffId,
			'RC04'			=> $sStaffName,
			'RC06'			=> $cmmt,
			);
		$arrCommentUpdate = $objModel->mTLSPRun('mTL_CommentUpdate',$arrParameter, 0,0);
		var_dump($arrCommentUpdate);
		$this->getHelper('viewRenderer')->setNoRender(); 
	}
	public function deletecmmtAction(){
		$objFunction = New Efy_Function_RecordFunctions();
		$objModel = new mtl_modSearch();
		$arrParameter = array('PkComments' 			=> $this->_request->getParam('PkComments',null)
							,'delimitorElement'		=> $this->_request->getParam('delimitorElement',null));  
		$arrResult = $objModel->mTLSPRun('mTL_CommentDelete',$arrParameter, 0,0);
		var_dump($arrResult);
		$this->getHelper('viewRenderer')->setNoRender();
	}
	public function readdocumentAction(){
		
		Zend_Loader::loadClass('Efy_UserCounter');
		$objconfig = new Efy_Init_Config();
		$userCounter = new Efy_UserCounter();
		$fileNameFull = $this->_request->getParam('id','');
		// $fileNameFull = '2014_10_29_0123000000723964!~!bieu mau nghi quyet 2905.doc.swf';
		$urlPath = $objconfig->_setAttachFileUrlPath();
		$fileLink = $this->getpathfile($urlPath, $fileNameFull);
		$userCounter->updateview();
		echo '<object width="100%" height="550" data="'.$fileLink.'"></object>';
		die;
	}

	public function downloaddocumentAction(){
		
		Zend_Loader::loadClass('Efy_UserCounter');
		$sesAccount = new Zend_Session_Namespace('Account');
		$objconfig = new Efy_Init_Config();
		$userCounter = new Efy_UserCounter();
		$fileNameFull = $this->_request->getParam('id','');
		if(!isset($sesAccount->id)) {
    		$this->_redirect('web/index/index/');
    	}
    	$userCounter->updatedown();		
		$sPathLink = realpath('public/attach-file');
		$arrFileName = explode("!~!",$fileNameFull);			
		$fileName    = $arrFileName[1];
		$fileID 	 = $arrFileName[0];
		$arrFileLink = explode('_',$fileID);
		$fileLink = $sPathLink.'/' . $arrFileLink[0] . "/" . $arrFileLink[1] . "/" . $arrFileLink[2] . "/" . $fileNameFull;

		$file_content = file_get_contents($fileLink);
		// Directly return the Response 
		$response = $this->getResponse();
		$response->setHeader('Content-Type', 'application/octet-stream')
		->setHeader('Content-Disposition', 'attachment;filename="' . $fileName . '"')
		->appendBody($file_content);
		$this->_helper->viewRenderer->setNoRender(true);
		return $response;
	}


}